package com.hj.dapp.config.advice;

import com.hj.dapp.common.resp.RestResp;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2023/12/29
 */
@RestControllerAdvice
public class RestRespAdvice<T> implements ResponseBodyAdvice<T> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getDeclaringClass().getPackage().getName().startsWith("com.hj.dapp") && !returnType.getMethod().getReturnType().isAssignableFrom(RestResp.class);
    }

    @Override
    public T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return (T) RestResp.ok(body);
    }
}
